﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Windows8Accelerator.Core.Xaml.Controls;

namespace Windows8Accelerator.Core.Xaml.Helpers
{
    public abstract class WebHelperBase
    {
        private static WebHelperBase _Instance;
        public static WebHelperBase Instance
        {
            get
            {
                if (_Instance == null)
                    _Instance = AssemblyHelper.CreateInstanceOfAccelerator<WebHelperBase>();
                return _Instance;
            }
        }

        public async Task<string> GetJsonAsync(string url, string user = null, string password = null)
        {
            return await GetStringAsync(url, "application/json", user , password );
        }

        public async Task<string> GetStringAsync(string url, string accept = null, string user = null, string password = null)
        {
            using (ProgressBarManager.NewWork())
            {
                return await InternalGetStringAsync(new Uri(url), accept, user, password);
            } 
        }

        public async Task<string> PostJsonAsync(string url, object postData, string user = null, string password = null)
        {
            var postDataAsJson = JsonConvert.SerializeObject(postData);
            return await PostStringAsync(url, postDataAsJson, "application/json", user, password);
        }

        public async Task<string> PostStringAsync(string url, string postData, string accept = null, string user = null, string password = null)
        {
            using (ProgressBarManager.NewWork())
            {
                return await InternalPostStringAsync(new Uri(url), postData, accept, user, password);
            }
        }

        protected abstract Task<string> InternalGetStringAsync(Uri uri, string accept, string user, string password);
        protected abstract Task<string> InternalPostStringAsync(Uri uri, object postData, string accept, string user, string password);

        public abstract Task<Stream> GetStreamAsync(Uri uri);
    }
}
